import { defineStore } from 'pinia'
import { computed, onMounted, ref, watch } from 'vue'
import { useTodosStore } from './todos'
import { getStorageSync, setStorageSync } from '../utils/storage'
import dayjs from 'dayjs'
import { patchColor } from '../utils/patchColor'

export const useSettingStore = defineStore('setting', () => {
  const todosStore = useTodosStore()

  // 自定义配置
  const customConfig = ref({
    autoComplete: true,    // 到期自动完成
    deleteDuringTime: -1   // 完成后多长时间后删除
  })

  // 所有标签
  const allLabels = ref<Label[]>([])

  onMounted(() => {
    getAllLabels()
  })

  // 添加标签
  const addLabel = (labelName: string) => {
    if (labelName.trim() === '') {
      uni.showToast({
        title: '请输入标签名称',
        icon: 'none'
      })
      return false
    }
    if (allLabels.value.some(label => label.name === labelName)) {
      uni.showToast({
        title: '标签已存在',
        icon: 'none'
      })
      return false
    }
    const label = {
      name: labelName,
      color: patchColor(labelName),
    }
    allLabels.value.unshift(label)
    return true
  }

  // 删除标签
  const deleteLabel = (labelName: string) => {
    allLabels.value = allLabels.value.filter(label => label.name !== labelName)
  }

  const todoList = computed(() => todosStore.todoList)

  // 定时更新计时器
  let timer: number | null = null

  // 定时更新周期
  const UPDATE_CIRCLE = 1000 * 30 // 30秒

  // 开启定时定期修改Todo状态
  const startTodoStatusHandler = (period: number = UPDATE_CIRCLE) => {
    // 更新Todo状态
    const updateTodoStatus = () => {
      // 当前秒级时间戳
      const nowTimeValue = dayjs().unix()

      todoList.value.forEach((todo) => {
        // 现在时间与todo的time的秒级时间戳差值
        const diffTime = nowTimeValue - dayjs(todo.time).unix()
        console.log(todo)

        // 到期自动完成 --- 如果时间戳小于当前时间戳，状态设为完成
        if (customConfig.value.autoComplete && todo.time === null && diffTime >= 0 && todo.status === 'doing') {
          todo.status = 'done'
          todo.doneTime = dayjs().unix()
        }

        // 定时删除已完成
        if (customConfig.value.deleteDuringTime >= 0 && todo.status === 'done' && todo.doneTime !== null) {
          // 是否超过设定的时间
          if (nowTimeValue - todo.doneTime >= customConfig.value.deleteDuringTime) {
            todosStore.deleteTodos([todo.id])
          }
        }
      })
    }

    updateTodoStatus()
    clearTodoStatusHandler()
  
    timer = setInterval(() => {
      updateTodoStatus()
    }, period)
  }

  // 清理定时器
  const clearTodoStatusHandler = () => {
    if (timer) clearInterval(timer)
    timer = null
  }

  const getAllLabels = () => {
    try {
      const res: Label[] | null = getStorageSync('labels')
      if (res) {
        allLabels.value = res
      }
    } catch (error) {
      console.log(error)
    }
  }

  const saveAllLabels = () => {
    try {
      setStorageSync<Label[]>('labels', allLabels.value)
    } catch (error) {
      console.log(error)
    }
  }

  const getCustomConfig = () => {
    try {
      const res: CustomConfig | null = getStorageSync('customConfig')
      if (res) {
        customConfig.value = res
      }
    } catch (error) {
      console.log(error)
    }
  }

  const saveCustomConfig = () => {
    try {
      setStorageSync<CustomConfig>('customConfig', customConfig.value)
    } catch (error) {
      console.log(error)
    }
  }

  watch(() => customConfig.value, saveCustomConfig, { deep: true })
  watch(() => allLabels.value, saveAllLabels, { deep: true })
  
  return {
    customConfig,
    allLabels,
    addLabel,
    deleteLabel,
    startTodoStatusHandler,
    clearTodoStatusHandler,
    getCustomConfig,
    getAllLabels,
  }
})